<template>
  <PageWrapper>
    <n-card :bordered="false" class="mb-3 proCard">
      <n-space align="center">
        <n-input-group style="width: 980px">
          <div style="margin-left: 10px !important;display: flex;align-items: center;">
            <div style="width: 160px;">二维码编号：</div>
            <n-input
              style="width: 100%;margin-left: 20px;"
              v-model:value="params.name"
              clearable
              placeholder="请输入二维码编号"
              @keyup.enter="reloadTable"
            />
          </div>

          <n-button type="primary" style="margin-left: 40px !important;" @click="reloadTable">
            <template #icon>
              <n-icon>
                <SearchOutlined />
              </n-icon>
            </template>
            查询
          </n-button>
        </n-input-group>
      </n-space>
    </n-card>
    <n-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="basicTableRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        virtual-scroll
      >
        <template #tableTitle>
          <n-space align="center">
            <n-button type="primary" @click="openCreateDrawer">
              <template #icon>
                <n-icon>
                  <FileAddOutlined />
                </n-icon>
              </template>
              批量生产二维码
            </n-button>
            <!-- @click="qrcodeExport" -->

            <!-- <n-button type="primary" @click="qrcodeExport">
              <template #icon>
                <n-icon>
                  <FileAddOutlined />
                </n-icon>
              </template>
              后台导出
            </n-button> -->

            <n-button type="primary" @click="openModal">
              <template #icon>
                <n-icon>
                  <FileAddOutlined />
                </n-icon>
              </template>
              导出
            </n-button>
            <!-- <n-button type="primary" @click="onBatchExport">
              <template #icon>
                <n-icon>
                  <FileAddOutlined />
                </n-icon>
              </template>
              导出
            </n-button> -->
            

            <!-- <n-button type="error" @click="openRemoveModal" :disabled="!rowKeys.length">
              <template #icon>
                <n-icon>
                  <DeleteOutlined />
                </n-icon>
              </template>
              删除
            </n-button> -->
          </n-space>
        </template>
      </BasicTable>
    </n-card>



    <CreateDrawer
      ref="createDrawerRef"
      :title="drawerTitle"
      :roleList="roleData"
      @change="reloadTable"
    />
    <basicModal @register="modalRegister" ref="modalRef" class="basicModal" @on-ok="okModal">
      <template #default>
        <BasicForm
          @register="register"
          @submit="handleSubmit"
          @reset="handleReset"
          class="basicForm"
        >
          <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
          </template>
        </BasicForm>
      </template>
    </basicModal>

  </PageWrapper>
</template>

<script lang="ts" setup>
  import { h, reactive, ref,unref, onMounted } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicColumn, BasicTable, TableAction } from '@/components/Table';
  // import { typelist,delType } from '@/api/device/type';
  import { basicModal, useModal } from '@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { jsonToSheetXlsx } from '@/components/Excel';

  import { qrcodelist,getbase641 } from '@/api/device/qrcode';

  import { FileAddOutlined, SearchOutlined } from '@vicons/antd';
  import CreateDrawer from './CreateDrawer.vue';
  import { columns } from './columns';
  import table2excel from 'js-table2excel';
import { title } from 'process';
import { Key } from '@vicons/ionicons5';
import { useGlobSetting } from '@/hooks/setting';
  const globSetting = useGlobSetting();
  const { uploadUrl } = globSetting;
  const uploadUrl1 = uploadUrl;

  const message = useMessage();
  const basicTableRef = ref();
  const rowKeys = ref([]);
  const rowKeysName = ref([]);
  const tableData = ref();
  const tableData2 = ref();
  const createDrawerRef = ref();
  const drawerTitle = ref('批量生产二维码');
  const roleData = ref([]);

  const params = reactive({
    name: '',
  });

  const modalRef = ref();

  const schemas: FormSchema[] = [
    {
      field: 'filename',
      component: 'NInput',
      label: '文件名',
      labelMessage: '导出的文件以该名称命名',
      giProps: {
        span: 1,
      },
      componentProps: {
        placeholder: '请输入文件名称',
        onInput: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ required: true, message: '请输入导出的文件名称', trigger: ['blur'] }],
    },
    {
      field: 'bookType',
      component: 'NSelect',
      label: '文件类型',
      componentProps: {
        placeholder: '请选择文件类型',
        options: [
          {
            label: 'xlsx',
            value: 'xlsx',
          }
        ],
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ required: true, message: '请选择文件类型', trigger: ['change'] }],
    },
  ];

  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({
        title: '导出数据',
  });
  const [register, { submit }] = useForm({
        gridProps: { cols: 1 },
        collapsedRows: 3,
        labelWidth: 120,
        layout: 'horizontal',
        // submitButtonText: '提交预约',
        showActionButtonGroup: false,
        schemas,
      });

  async function okModal() {
    const formRes = await submit();
    if (formRes) {
      modalRef.value.closeModal();
      message.success('提交成功');
    } else {
      message.error('验证失败，请填写完整信息');
      modalRef.value.setSubLoading(false);
    }
  }

  // const actionColumn: BasicColumn = reactive({
  //   width: 150,
  //   title: '操作',
  //   key: 'action',
  //   fixed: 'right',
  //   align: 'center',
  //   render(record) {
  //     return h(TableAction as any, {
  //       actions: [
  //         // {
  //         //   label: '删除',
  //         //   onPositiveClick: handleDelete.bind(null, record),
  //         //   isConfirm: true,
  //         //   confirmContent: '您确定要删除吗？',
  //         // },
  //         // {
  //         //   label: '编辑',
  //         //   onClick: handleEdit.bind(null, record),
  //         // },
  //       ],
  //     });
  //   },
  // });

  const loadDataTable = async (res) => {
    const result = await qrcodelist({ ...params, ...res });
    tableData.value = result.list;
    // console.log(tableData.value);
    return result;
  };

  function onCheckedRow(keys) {
    rowKeys.value = keys;
    rowKeysName.value = tableData.value
      .filter((item) => {
        return keys.includes(item.id);
      })
      .map((item) => {
        return item.username;
      })
      .join('，');
  }

  function reloadTable() {
    basicTableRef.value.reload();
  }



  function qrcodeExport() {
    //用浏览器打开页面
    window.open(uploadUrl1+"/api/excel/qrcodeexport");
  }

  const onBatchExport = () => {
    const column = [
      {
        title:"二维码编号",
        key:"qrcode_number",
        type: "text"
      },
      {
        title:"设备编号",
        key:"device_number",
        type: "text"
      },
      {
        title:"设备名称",
        key:"device_name",
        type: "text"
      },
      {
        title: "二维码",
        Key: "qrcode_url",
        type: "image",
        width: 40,
        height: 40
      }
    ];

    var tableDataJson = [];

    var imgUrl = tableData.value[0].qrcode_url;


    // console.log("看看事");
    // console.log(imgUrl);

    // console.log("开始了嗷看看");

    for(let i=0;i<tableData.value.length;i++){
      tableDataJson.push({'qrcode_number':tableData.value[i].qrcode_number,'device_number':tableData.value[i].device_number,'device_name':tableData.value[i].device_name,'qrcode_url':tableData.value[i].qrcode_url});
    }

    //把json数据传到后台把图片变为base64位格式
    getbase641(tableDataJson).then((res) => {
      console.log("查看一下res");
      console.log(res)
      let tableDatas = JSON.parse(JSON.stringify(res));

      table2excel(column,tableDatas,'数据');
    });

    
    // let tableDatas = JSON.parse(JSON.stringify(tableDataJson));
    // console.log("撒旦解放立刻撒娇的开发了就是打卢克");
    // console.log(tableDatas)
    // table2excel(column,tableDatas,'数据');

  }


  function handleReset(){
    // formRef.value.restoreValidation();
    // formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  function handleSubmit(values: Recordable) {
    // console.log("打印一下再")
    // console.log(values);
    // 默认Object.keys(data[0])作为header
    const { filename, bookType } = values;
    console.log("查看依稀啊");
    console.log(bookType);

    var tableDataJson = [];

    console.log(tableData);
    
    for(let i=0;i<tableData.value.length;i++){
      tableDataJson.push({'qrcode_number':tableData.value[i].qrcode_number,'device_number':tableData.value[i].device_number,'device_name':tableData.value[i].device_name,'qrcode_url':tableData.value[i].qrcode_url});
    }

    //把json数据传到后台把图片变为base64位格式
    // getbase641(tableDataJson).then((res) => {
      // console.log("查看一下res");
      // console.log(res)
      tableData2.value = tableDataJson;
      jsonToSheetXlsx({
        data: unref(tableData2),
        header: {
          qrcode_number:'二维码编号',
          device_number:'设备编号',
          device_name:'设备名称',
          qrcode_url:'二维码',
        },
        filename: `${filename.split('.').shift()}.${bookType}`,
        write2excelOpts: {
          bookType,
        },
        json2sheetOpts: {
          //指定顺序
          header:['qrcode_number','device_number','device_name','qrcode_url']
        }

      });
      message.success("导出成功");
    // });

    

    
  }

  function openCreateDrawer() {
    const { openDrawer } = createDrawerRef.value;
    openDrawer();
  }

  // function handleEdit(record: Recordable) {
  //   console.log('点击了编辑', record);
  //   drawerTitle.value = '编辑用户';
  //   const { openDrawer } = createDrawerRef.value;
  //   openDrawer(record.id);
  // }

  // function handleDelete(record: Recordable) {
  //   delType({ id: record.id }).then(() => {
  //     message.success('删除成功');
  //     reloadTable();
  //   });
  // }

  onMounted(async () => {
    
  });
</script>

<style lang="less" scoped></style>
